package com.example.triprec.ui.activity;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.triprec.R;
import com.example.triprec.common.Result;
import com.example.triprec.dao.CollectDao;
import com.example.triprec.entity.Collect;
import com.example.triprec.entity.User;
import com.example.triprec.ui.adapter.MyCollectionAdapter;
import com.example.triprec.utils.CurrentUserUtils;

import java.util.ArrayList;
import java.util.List;

public class MyCollectionsActivity extends AppCompatActivity {

    private ImageView ivBack;
    private RecyclerView rvCollections;
    private LinearLayout layoutEmpty;

    private MyCollectionAdapter collectionAdapter;
    private List<Collect> collectionList = new ArrayList<>();
    private User currentUser;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_collections);

        initViews();
        setupListeners();
    }

    @Override
    protected void onResume() {
        super.onResume();
        initData();
    }

    private void initViews() {
        ivBack = findViewById(R.id.iv_back);
        rvCollections = findViewById(R.id.rv_collections);
        layoutEmpty = findViewById(R.id.layout_empty);

        // 设置RecyclerView
        rvCollections.setLayoutManager(new LinearLayoutManager(this));
        collectionAdapter = new MyCollectionAdapter(collectionList);
        rvCollections.setAdapter(collectionAdapter);
    }

    private void setupListeners() {
        // 返回按钮点击事件
        ivBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        // 收藏项点击事件
        collectionAdapter.setOnItemClickListener(new MyCollectionAdapter.OnItemClickListener() {
            @Override
            public void onCancelClick(Collect collect, int position) {
                showCancelConfirmDialog(collect, position);
            }

            @Override
            public void onViewDetailClick(Collect collect) {
                navigateToScenicDetail(collect);
            }
        });
    }

    private void initData() {
        // 获取当前登录用户
        try {
            currentUser = CurrentUserUtils.getCurrentUser();
            loadCollections();
        } catch (Exception e) {
            Toast.makeText(this, "获取用户信息失败", Toast.LENGTH_SHORT).show();
            finish();
        }
    }

    private void loadCollections() {
        Result<List<Collect>> result = CollectDao.getCollectsByUserId(currentUser.getId());
        if (result.isSuccess()) {
            collectionList.clear();
            if (result.getData() != null && !result.getData().isEmpty()) {
                collectionList.addAll(result.getData());
                layoutEmpty.setVisibility(View.GONE);
                rvCollections.setVisibility(View.VISIBLE);
            } else {
                layoutEmpty.setVisibility(View.VISIBLE);
                rvCollections.setVisibility(View.GONE);
            }
            collectionAdapter.notifyDataSetChanged();
        } else {
            Toast.makeText(this, result.getMessage(), Toast.LENGTH_SHORT).show();
        }
    }

    private void showCancelConfirmDialog(Collect collect, int position) {
        new AlertDialog.Builder(this)
                .setTitle("确认取消收藏")
                .setMessage("确定要取消收藏" + collect.getScenic().getName() + "吗？")
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        cancelCollection(collect, position);
                    }
                })
                .setNegativeButton("取消", null)
                .show();
    }

    private void cancelCollection(Collect collect, int position) {
        Result<Void> result = CollectDao.cancelCollectById(collect.getId());
        if (result.isSuccess()) {
            collectionList.remove(position);
            collectionAdapter.notifyItemRemoved(position);
            collectionAdapter.notifyItemRangeChanged(position, collectionList.size() - position);

            // 检查是否所有收藏都已取消
            if (collectionList.isEmpty()) {
                layoutEmpty.setVisibility(View.VISIBLE);
                rvCollections.setVisibility(View.GONE);
            }

            Toast.makeText(this, "取消收藏成功", Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(this, result.getMessage(), Toast.LENGTH_SHORT).show();
        }
    }

    private void navigateToScenicDetail(Collect collect) {
        Intent intent = new Intent(this, ScenicDetailActivity.class);
        intent.putExtra("scenic_id", collect.getScenicId());
        startActivity(intent);
    }
} 